package com.jian.socks5.udp.codec;

import com.jian.socks5.udp.DefaultSocks5UDPPacket;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.handler.codec.socksx.v5.Socks5AddressEncoder;
import io.netty.handler.codec.socksx.v5.Socks5AddressType;

import java.util.List;

/***
 * Socks5 udp报文编码器
 * @author Jian
 * @date 2021.06.21
 */
@ChannelHandler.Sharable
public class Socks5UDPResponseEncoder extends MessageToMessageEncoder<DefaultSocks5UDPPacket> {

    @Override
    protected void encode(ChannelHandlerContext ctx, DefaultSocks5UDPPacket msg, List<Object> out) throws Exception {
        ByteBuf buffer = ctx.alloc().buffer();
        buffer.writeShort(msg.getRSV());
        buffer.writeByte(msg.getFRAG());
        Socks5AddressType bndAddrType = msg.getSocks5AddressType();
        buffer.writeByte(bndAddrType.byteValue());
        Socks5AddressEncoder.DEFAULT.encodeAddress(bndAddrType, msg.getDstAddr(), buffer);
        buffer.writeShort((short)msg.getDstPort());
        buffer.writeBytes(msg.getData());
        DatagramPacket datagramPacket = new DatagramPacket(buffer,msg.getRecipient(),msg.getSender());
        out.add(datagramPacket);
    }
}
